
<?php
/**
 * Created by Spinatiev Ivan
 * User: developer
 * Date: 8/30/12
 * Time: 10:48 AM
 * To change this template use File | Settings | File Templates.
 */
class Page_Be_Products_Products extends Page
{
    /**
     * @var Db_Products_Products
     */
    protected $tableObject;

    function __construct() {
        $this->idTableObject = get('id', 'int');
        $this->actionsTableObject = array(
            'addEditAction', 'saveAction', 'editPhotosAction', 'uploadPhotosAction'
        );
        $this->classTableObject = 'Db_Products_Products';
        parent::__construct();
    }

    public function defaultAction() {
		if (perm('PRODUCTS_EDIT')) {
			$this->addBreadcrumb(t(T_FORM_BUTTON, 'add'), '?action=addEdit');
		}
		self::$TPL->appendJsFile('admin/products');
        self::$TPL->setBodyTemplate('list_products');
        return array(
            'type' => 'display'
        );
    }

    public function addEditAction() {
		perm('PRODUCTS_EDIT', '/products/products');
        if (!empty($this->tableObject->objectArray->id)) {
            $this->addBreadcrumb(t(T_FORM_BUTTON, 'edit') . ' &quot;' . t(T_PRODUCTS_TITLE, $this->tableObject->objectArray->p_name) . '&quot;', '#', true);
            self::$TPL->assign('products', $this->tableObject->objectArray);
        } else {
            $this->addBreadcrumb(t(T_FORM_BUTTON, 'add'), '#', true);
        }
		if(!empty($this->idTableObject)) {
			$productUsedThemes = Db_Products_Themes::getUsedThemes($this->tableObject->objectArray->id);
			self::$TPL->assign('productUsedThemes', $productUsedThemes);
		}

        $allSizes = Db_Products_Sizes::findAllArray();
        self::$TPL->assign('allSizes', $allSizes);

        $allCoverTypes = Db_Products_CoverTypes::findAllArray();
        self::$TPL->assign('allCoverTypes', $allCoverTypes);

		$allTags = Db_Products_Tags::findAllArray();
		self::$TPL->assign('allTags', $allTags);

		$productTags = Db_Products_Products::getProductTags($this->tableObject->id);
		self::$TPL->assign('productTags', $productTags);

		$sizeId = (!empty($this->tableObject->objectArray->p_size_id) ? $this->tableObject->objectArray->p_size_id : $allSizes[0]['id']);

		$productGroupStyles = Db_Products_GroupStyles::loadForProduct($this->tableObject->id);
		self::$TPL->assign('productGroupStyles', $productGroupStyles);

		$enumVar = $this->tableObject->getEnumValues("p_type");
		self::$TPL->assign('p_type', $enumVar);
		if(isset($this->tableObject->objectArray->p_type) && $this->tableObject->objectArray->p_type == 'book') {
			$productThemes = Db_Products_Themes::getValidThemes($this->tableObject->id, $sizeId);
		} else {
			$productThemes = Db_Products_Themes::getAllThemesByProductId($this->tableObject->id);
			self::$DEBUG->addPrivateVar($productThemes);
		}
		self::$TPL->assign('productThemes', $productThemes);

		$productCategories = Db_Products_Products::getProductCategories($this->tableObject->id);
		self::$TPL->assign('productCategories', $productCategories);

		self::$TPL->appendJsFile('admin/products');
        self::$TPL->setBodyTemplate('add_edit_products');
        return array(
            'type' => 'display'
        );
    }

	public function editPhotosAction() {
		if ($this->tableObject->id) {
			$this->addBreadcrumb(t(T_FORM_BUTTON, 'edit') . ' &quot;' . t(T_PRODUCTS_TITLE, $this->tableObject->objectArray->p_name) . '&quot;', '?action=addEdit&id=' . $this->idTableObject );
			$this->addBreadcrumb(t(T_FORM_BUTTON, 'edit_photos') . ' &quot;' . t(T_PRODUCTS_TITLE, $this->tableObject->objectArray->p_name) . '&quot;', '?action=editPhotos&id=' . $this->idTableObject, true );
			$allProductThemes = Db_Products_Products::getProductPhotos($this->tableObject->id);
			if (!is_array($allProductThemes) || 0===count($allProductThemes)) {
				$this->error = true;
				$this->message = t(T_FORM_ERROR, 'product_has_no_photos');
				return array(
					'type' => 'redirect',
					'content' => '?action=addEdit&id=' . $this->tableObject->id
				);
			}
			self::$TPL->appendJsFile('admin/products');
			self::$TPL->assign('allProductThemes', $allProductThemes);
			self::$TPL->assign('filePath', self::$PROJECT['pr_resources_live']);
			self::$TPL->assign('product', $this->tableObject);
			self::$TPL->setBodyTemplate('edit_product_photos');
			return array(
				'type' => 'display'
			);
		} else {
			$this->error = true;
			$this->message = t(T_FORM_ERROR, 'unknown_error_occurred');
			return array(
				'type' => 'redirect',
				'query' => false
			);
		}
	}

	public function ajaxLoadProductsDataAction() {
		$allColumns = array('nr', 'p_name', 's_name', 'p_type', 'ct_name', 'te_name', 'action');
		$searchColumns = array('p_name', 's_name', 'p_type', 'ct_name', 'te_name');

		list($searchQuery,$orderBy, $limit) = Utils::getSqlQueriesForPagination($allColumns, $searchColumns, 'Db_Products_Products', 'getTotalProducts');
		$allProducts = Db_Products_Products::getAllProducts($limit, $searchQuery, $orderBy);
		self::$TPL->assign('allProducts', $allProducts);

		$productsCategories = Db_Products_Products::getProductsCategories();
		self::$TPL->assign('productsCategories', $productsCategories);

		return array(
			'type' => 'encoded_json',
			'content' => self::$TPL->display('json_list_products', true)
		);
	}


	public function uploadPhotosAction() {
		perm('PRODUCTS_EDIT', '/products/products');
		$status = array();
		// If a gallery for this product already exists, we should use that gallery.
		//This query will return 'false' if such a gallery does not exist, and the gallery itself if it does
		$existingGallery = Db_Products_PhotosGalleries::findByFields( array(
			'pg_owner_id' => $this->tableObject->id,
			'pg_gallery_type' => 'product'
		));
		//The file inputs have the 'photo[][]' as their name. If data with such name does not exist, we have nothing to do here
		if (isset($_FILES['photo'])) {
			$files = array();
			//Converting the files into a usable format, like grouping the photos by theme id in pairs
			//of a cropped photo and screen photo, to be used with the upload function
			foreach ($_FILES['photo'] as $property=>$themePhotos){
				foreach ($themePhotos as $themeId=>$photoPair) {
					foreach ($photoPair as $nr=>$propertyValue) {
						$files[$themeId][$nr][$property] = $propertyValue;
					}
				}
			}

			$photosBatch = array();
			foreach ($files as $themeId=>$photoPair) {
				//if at least one file for this theme was supplied
				if (PHP_FILE_NOT_UPLOADED_ERROR != $photoPair[0]['error'] || PHP_FILE_NOT_UPLOADED_ERROR != $photoPair[1]['error']) {
					//Init the DB gallery object
					if ($existingGallery) {
						$gallery = new Db_Products_PhotosGalleries($existingGallery->id);
					} else {
						$gallery = new Db_Products_PhotosGalleries();
					}
					//populate it with data
					$gallery->pg_owner_id = $this->tableObject->id;
					$gallery->pg_gallery_type = 'product';
					$gallery->pg_name = t(T_PRODUCTS, 'gallery_for') . ' ' . t(T_PRODUCTS_TITLE, $this->tableObject->objectArray->p_name);
					$gallery->save(true);

					/* we need to have an array of paths scheduled for deletion, that's because we must remove the file
					only if the upload was successful, however, if the upload is successful, the DB entry would contain
					the new paths, and the old ones would be out of vision */
					$scheduledForUnlink=array();

					//Query for a possibly existing photo for this product and theme
					$existingProductPhoto = Db_Products_Products::getProductPhotoForTheme($this->tableObject->id, $themeId);
					$photoPair['photoId'] = false;
					//and if such a photo does indeed exist
					$filename = '';
					if (PHP_FILE_NOT_UPLOADED_ERROR != $files[$themeId][0]['error']) {
						$filename = $files[$themeId][0]['name'];
					}
					if (PHP_FILE_NOT_UPLOADED_ERROR != $files[$themeId][1]['error']) {
						$filename .= (', ' . $files[$themeId][1]['name']);
					}
					if (isset($existingProductPhoto->pt_photo_id)) {
						$photoPair['photoId'] = $existingProductPhoto->pt_photo_id;
						//do some cleanup
						$existingPhoto = new Db_Products_Photos($existingProductPhoto->pt_photo_id);
						if ($existingPhoto->objectArray->id) {
							if (PHP_FILE_NOT_UPLOADED_ERROR != $files[$themeId][0]['error']) {
								$scheduledForUnlink[] = PUBLIC_RESOURCES_PATH . ($existingPhoto->objectArray->ph_path) . ($existingPhoto->objectArray->ph_name);
								$filename = $files[$themeId][0]['name'];
							}
							if (PHP_FILE_NOT_UPLOADED_ERROR != $files[$themeId][1]['error']) {
								$scheduledForUnlink[] = PUBLIC_RESOURCES_PATH . ($existingPhoto->objectArray->ph_path) . ($existingPhoto->objectArray->ph_resized);
								$filename .= ', ' . $files[$themeId][1]['name'];
							}
						}
					}

					//Upload the photo
					$result = Utils::uploadFile($photoPair, PRODUCTS_PHOTOS_PRODUCT_PATH, $this->tableObject->id, array('jpg', 'png', 'gif'), false, 0, true, $gallery->id);
					if ($result['error'] || !isset($result['data']['ph_id'])) {
						$this->error = true;
						if (isset($result['message']) && strlen($message=$result['message'])) {
							$status[] = "{$filename}: {$message}";
						} else {
							$status[] = "{$filename}: " . t(T_FORM_ERROR, 'unknown_error_occurred');
						}
					} else {
						//unlink the scheduled paths
						foreach ($scheduledForUnlink as $path) {
							@unlink($path);
						}
						//Accumulate data for photo update
						$photosBatch[] = array(
							'pt_photo_id' => $result['data']['ph_id'],
							'pt_product_id' => $this->tableObject->id,
							'pt_theme_id' => $themeId
						);
						$status[] = "{$filename}: " . t(T_FORM_MSG, 'success');
					}
				}
			}
			self::$DB->insertBatch(TAB_PRODUCT_THEME_PHOTOS, $photosBatch, true);
			$this->message = implode('<br/>', $status);
		} else {
			$this->error = true;
			$this->message = t(T_FORM_ERROR, 'unknown_error_occurred');
		}
		return array(
			'type' => 'redirect',
			'content' => '?action=addEdit&id=' . $this->tableObject->id
		);
	}

    public function saveAction() {
		perm('PRODUCTS_EDIT', '/products/products');
		//TO DO: check if photos exist for previously selected but now unselected themes and clean them
        $productsName = strtolower(post('p_name', 'string'));
        $this->message = t(T_FORM_MSG, 'success');
        if (!empty($productsName)) {
            if (!empty($this->idTableObject)) {
                $this->tableObject->id = $this->idTableObject;
            }
		    $themes = post('pt_theme_id', 'array');
			$productCoverTypes = post('p_cover_type_id', 'int');
			$productTypes = post('p_type');
			$productGroupStile = post('product_group_style', 'int');
			$productIsEnvelope = post('p_is_envelope', 'int');
			$productDefaultUrl = strtolower(post('p_default_url'));
			$categories = post('prc_category_ids', 'array');
			$tags = post('prt_id', 'array');

			$categoriesValid = Db_Products_Categories::verifyIsValidCategories($categories);

			if($categoriesValid > 1) {
				$this->error = true;
				$this->message = t(T_FORM_ERROR, 'check_other_category');
				if($this->tableObject->id) {
					return array(
						'type' => 'redirect',
						'content' => '?action=addEdit&id=' . $this->tableObject->id
					);
				}
			}


			if ($productTypes == 'envelope') {
            	$productCoverTypes = 0;
				$productGroupStile = 0;
				$productIsEnvelope = 0;
				$productDefaultUrl = "";
				$tags = array();
			}

			//check if url is unique
			if ($this->tableObject->checkProductUrlIsUnique($productDefaultUrl, $this->tableObject->id)) {
				$this->error = true;
				$this->message = t(T_FORM_ERROR, 'url_is_not_unique');
				return array(
					'type' => 'redirect',
					'content' => '?action=addEdit&id=' . $this->tableObject->id
				);
			}

            $this->tableObject->p_name = $productsName;
			$this->tableObject->p_description = post('p_description');
			$this->tableObject->p_long_description = post('p_long_description');
            $this->tableObject->p_size_id = post('p_size_id', 'int');
            $this->tableObject->p_type = $productTypes;
            $this->tableObject->p_cover_type_id = $productCoverTypes;
			$this->tableObject->p_group_style = $productGroupStile;
			$this->tableObject->p_is_envelope = $productIsEnvelope;
			$this->tableObject->p_default_url = $productDefaultUrl;
            if (!$this->tableObject->save()) {
               $this->error = true;
			   $this->message = t(T_FORM_ERROR, 'unknown_error_occurred');
            } else {
				/* If the user specified he wants to also deleted all related data */
				$themesSuccess = true;
				if (!empty($themes)) {
					if ('delete'==post('deleteDependencies', 'string')) {
						$photos = Db_Products_Products::deleteProductThemeDataRecursively($this->tableObject->id, $themes);
						/* get the ids of the photos belonging to the now unchecked themes */
						foreach ($photos as $photo){
							@unlink(PUBLIC_RESOURCES_PATH . ($photo->ph_path) . ($photo->ph_name));
							@unlink(PUBLIC_RESOURCES_PATH . ($photo->ph_path) . ($photo->ph_resized));
						}
					}
					$themesSuccess = Db_Products_Products::rewriteProductThemes($this->tableObject->id, $themes);
				} else {
					Db_Products_Themes::deleteProductsThemes($this->tableObject->id);
				}
				if (!Db_Products_Products::rewriteProductTags($this->tableObject->id, $tags) ||
					!Db_Products_Products::rewriteProductCategories($this->tableObject->id, $categories) ||
					!$themesSuccess) {
					$this->error = true;
					$this->message = t(T_FORM_ERROR, 'unknown_error_occurred');
				}
            }
         } else {
            $this->error = true;
            $this->message = t(T_FORM_ERROR, 'unknown_error_occurred');
        }
		Db_Cms_Pages::updateProductPageUrls();
        return array(
            'type' => 'redirect',
            'content' => '?action=addEdit&id=' . $this->tableObject->id
        );
    }

    public function deleteAction()  {
		perm('PRODUCTS_EDIT', '/products/products');
        $this->message = t(T_FORM_MSG, 'success');
        if (!empty($this->idTableObject)) {
            if (!Db_Products_Products::abstractDelete($this->idTableObject)) {
                $this->error = true;
                $this->message = t(T_FORM_ERROR, 'unknown_error_occurred');
            }
        } else {
            $this->error = true;
            $this->message = t(T_FORM_ERROR, 'unknown_error_occurred');
        }
		Db_Cms_Pages::updateProductPageUrls();
        return array(
            'type' => 'redirect',
            'query' => false
        );
    }

	public function ajaxGetProductUrlAction() {
		$productsName = strtolower(post('productName', 'string'));
		$categoryName = strtolower(post('categoryName', 'string'));
	  	$categoryName = ($categoryName == "null") ? "" : $categoryName;
		$countryLang = conf('COUNTRY_LANG_ID');

		$isTranslationCategory = Db_Locale_Translations::getContentTranslationByLangKeyModule($countryLang, $categoryName, 'category_title');
		$categoryForUrl = ($isTranslationCategory) ? $isTranslationCategory : $categoryName;

		$isTranslationName = Db_Locale_Translations::getContentTranslationByLangKeyModule($countryLang, $productsName, 'products_title');
		$productNameForUrl = ($isTranslationName) ? $isTranslationName : $productsName;

		$productUrl = Utils::filterUrl($categoryForUrl."-".$productNameForUrl).".php";
		return array(
			'type' => 'json',
			'content' => $productUrl
		);
	}

	public function getValidThemesAction() {
		$productId = post('p_product_id', 'int');
		$sizeId= post('p_size_id', 'int');
		$products = new Db_Products_Products($productId);
		if($products->objectArray->p_type == 'book') {
			$productThemes = Db_Products_Themes::getValidThemes($productId, $sizeId);
		} else {
			$productThemes = Db_Products_Themes::getAllThemesByProductId($productId);
		}

		self::$TPL->assign('productThemes', $productThemes);
		if(!$productThemes) {
			$this->error = true;
		}
		return array(
			'type' => 'encoded_json',
			'content' => $this->jsonResult($this->error, true, self::$TPL->display('ajax_themes_section', true))
		);
	}

	public function checkProductPreOrderAction() {
		$productId = post('p_product_id', 'int');
		$existPreOrder= Db_Products_MemoryListProducts::findByField('', $productId);
		if(!$existPreOrder) {
			$this->error = true;
		}
		return array(
			'type' => 'encoded_json',
			'content' => $this->jsonResult($this->error, true, !$this->error)
		);
	}

	public function getUsedThemesAction() {
		$productId = post('p_product_id', 'int');
		$sizeId= Db_Products_Products::findByField('id', $productId);
		$themes = array();
		if(!empty($sizeId) && !empty($productId)) {
			$productThemes = Db_Products_Themes::getValidThemes($productId, $sizeId->p_size_id);
			if(!empty($productThemes)) {
				foreach($productThemes as $theme) {
					if(isset($theme['pt_theme_id'])) {
						if(isset($theme['pt_theme_id']) && isset($theme['used']) && $theme['used'] == true) {
							$themes[] = array($theme['pt_theme_id'], $theme['te_name']);
						}
					}
				}
			}
		} else {
			$this->error = true;
		}

		return array(
			'type' => 'encoded_json',
			'content' => $this->jsonResult(!$this->error, true, $themes)
		);
	}

}